import React, { ReactElement, useEffect, useState } from 'react'
import { Menu, Dropdown, Skeleton, Modal, message, Empty } from 'antd'
import { EllipsisOutlined, PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { connect } from 'react-redux'
import { UserInfo } from '@components/schema/basic'

import style from './index.module.less'
import { awaitWrap } from '@src/assets/js/tool'
import { getDepartmentTreeRequest, delDepartmentRequest } from './ajax'
import { DepartmentSchema } from '@src/components/schema/departmentSchema'
import classNames from 'classnames'
import DetailModal from './components/detailModal'
import { TreeData } from '@src/components/schema/tree'
import { INIT_BASIC_STATE } from '@redux/reducers/basic';
import { tenantCode } from '@src/assets/js/config'

const { confirm } = Modal

interface ItemProps {
  data: DepartmentSchema
  current: DepartmentSchema | null
  onChange: (v: DepartmentSchema) => void
  onEdit: (v: DepartmentSchema) => void
  refreshData: () => void
}

// 删除请求
async function delDepartment (id: string, refreshData: () => void): Promise<void> {
  const hide = message.loading('删除中', 120)
  const [e] = await awaitWrap(delDepartmentRequest(id))
  hide()
  if (e === null) {
    refreshData()
  }
}

// 删除确认
function confrimDel (d: DepartmentSchema, refreshData: () => void): void {
  confirm({
    icon: <ExclamationCircleOutlined />,
    content: `您确定要删除 ${d.name} 吗？`,
    onOk: () => {
      delDepartment(d.id, refreshData).catch(e => console.error(e))
    }
  })
}

function Item ({ data, current, onChange, onEdit, refreshData }: ItemProps): ReactElement {
  const menu = (
    <Menu>
      <Menu.Item key="0" onClick={() => onEdit(data)}>编辑</Menu.Item>
      <Menu.Item key="1" onClick={() => confrimDel(data, refreshData)}>删除</Menu.Item>
    </Menu>
  )
  const isActive = current !== null && current.id === data.id
  return (
    <div className={style['department-block']}>
      <div className={classNames(style['department-line'], { [style.active]: isActive })} onClick={() => onChange(data)}>
        <span className={style['department-title']}>{data.name}</span>
        <Dropdown overlay={menu} trigger={['click']}>
          <span className={style['department-btn']} onClick={e => e.stopPropagation()}><EllipsisOutlined /></span>
        </Dropdown>
      </div>
      <div className={style['son-department']}>
        {data.children.map(li => <Item data={li} key={li.id} current={current} onChange={onChange} onEdit={onEdit} refreshData={refreshData} />)}
      </div>
    </div>
  )
}

async function getDepartmentTree (code: string, setTrees: (v: DepartmentSchema[]) => void, onChange: (v: DepartmentSchema) => void, setLoading: (v: boolean) => void, onInit: (v: DepartmentSchema[]) => void): Promise<void> {
  setLoading(true)
  const [e, d] = await awaitWrap(getDepartmentTreeRequest(code))
  setLoading(false)
  if (e === null && d !== null) {
    setTrees(d)
    onInit(d)
    onChange(d[0])
  }
}

interface Props {
  userInfo: UserInfo
  value: DepartmentSchema | null
  onChange: (v: DepartmentSchema) => void
  onInit: (v: DepartmentSchema[]) => void
  treeData: TreeData[]
}

function Main ({ userInfo, value, onChange, onInit, treeData }: Props): ReactElement {
  const [trees, setTrees] = useState<DepartmentSchema[]>([])
  const [visible, setVisible] = useState(false)
  const [modifyData, setModifyData] = useState<DepartmentSchema|null>(null)
  const [loading, setLoading] = useState(false)
  const refreshData = function (): void {
    getDepartmentTree(tenantCode, setTrees, onChange, setLoading, onInit).catch(e => console.error(e))
  }
  useEffect(() => {
    refreshData()
  }, [])
  return (
    <Skeleton loading={loading} active>
      <DetailModal treeData={treeData} data={modifyData} visible={visible} tenantCode={tenantCode} hide={() => { setVisible(false); setModifyData(null) }} refreshData={refreshData} />
      {trees.length === 0 && !loading ? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /> : null}
      {trees.map(li => {
        const isActive = value !== null && value.id === li.id
        return (
          <div key={li.id}>
            <div className={classNames(style.title, { [style.active]: isActive })} onClick={() => onChange(li)}>{li.name}</div>
            {li.children.map((o) => {
              return <Item data={o} key={o.id} current={value} onChange={onChange} refreshData={refreshData} onEdit={(li) => {
                setModifyData(li)
                setVisible(true)
              }} />
            })}
          </div>
        )
      })}
      <button className={style['add-btn']} onClick={() => setVisible(true)}>
        <PlusOutlined />
        <span className={style['add-btn-title']}>添加部门</span>
      </button>
    </Skeleton>
  )
}

export default connect((state: { basic: INIT_BASIC_STATE }) => {
  return {
    userInfo: state.basic.userInfo
  }
}, dispatch => {
  return {}
})(Main)
